﻿using BCCommon;
using BCCommon.Enums;
using BCData.MakeStaticPagingComponent.PageTemplateAttachment;
using BCDto.MakeStaticPagingComponent.PageTemplateAttachment;
using BCEntity.MakeStaticPagingComponent.PageTemplateAttachment;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCData.MakeStaticPagingComponent.PageTemplate;
using System.IO;
using Microsoft.Extensions.Configuration;
using BCDto.Sim.Admin.Admin;

namespace BCService.MakeStaticPagingComponent.PageTemplateAttachmentService
{
    public class PageTemplateAttachmentService : IPageTemplateAttachmentService
    {
        private readonly IDatabaseContext databaseContext;
        private readonly IConfiguration configuration;
        private readonly IRedisService redisService;
        private readonly IPageTemplateAttachmentData pageTemplateAttachmentData;
        private readonly IPageTemplateData pageTemplateData;
        private readonly string key = string.Format("{0}", EntityNameConst.PageTemplateAttachmentEntity);

        public PageTemplateAttachmentService(IDatabaseContext databaseContext,
            IConfiguration configuration,
            IRedisService redisService,
            IPageTemplateAttachmentData pageTemplateAttachmentData,
            IPageTemplateData pageTemplateData)
        {
            this.databaseContext = databaseContext;
            this.configuration = configuration;
            this.redisService = redisService;
            this.pageTemplateAttachmentData = pageTemplateAttachmentData;
            this.pageTemplateData = pageTemplateData;
        }

        #region 检查页面模板附件是否存在
        public bool Exists(int pageTemplateAttachmentId)
        {
            return this.pageTemplateAttachmentData.Exists(pageTemplateAttachmentId).GetAwaiter().GetResult();
        }
        #endregion

        #region 添加页面模板附件
        public PageTemplateAttachmentDto Add(PageTemplateAttachmentRequestDto requestDto,AdminDto adminDto)
        {
            if (!this.pageTemplateData.CheckPageTemplateExists(requestDto.PageTemplateId))
            {
                throw new ArgumentException("此页面模板不存在!");
            }
            var pageTemplateEntity = this.pageTemplateData.Get(requestDto.PageTemplateId);
            var entity = requestDto.As<PageTemplateAttachmentEntity>();
            entity.WebsiteTemplateId = pageTemplateEntity.WebsiteTemplateId;
            entity.CreateAdminName = adminDto.FullName;
            entity.CreateAdminId = adminDto.AdminId;

            var result = this.pageTemplateAttachmentData.Add(entity).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result.As<PageTemplateAttachmentDto>();
        }
        #endregion

        #region 修改页面模板附件
        public PageTemplateAttachmentDto Update(PageTemplateAttachmentPutDto putDto, AdminDto adminDto)
        {
            if (!this.Exists(putDto.PageTemplateAttachmentId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            if (!this.pageTemplateData.CheckPageTemplateExists(putDto.PageTemplateId))
            {
                throw new ArgumentException("此页面模板不存在!");
            }
            var pageTemplateEntity = this.pageTemplateData.Get(putDto.PageTemplateId);
            var entity = putDto.As<PageTemplateAttachmentEntity>();
            entity.WebsiteTemplateId = pageTemplateEntity.WebsiteTemplateId;
            entity.EditAdminName = adminDto.FullName;
            entity.EditAdminId = adminDto.AdminId;
            var result = this.pageTemplateAttachmentData.Update(entity).GetAwaiter().GetResult().As<PageTemplateAttachmentDto>();
            this.redisService.DeleteMultipleKey(key, false);
            return result;
        }
        #endregion

        #region 删除页面模板附件
        public bool Delete(int pageTemplateAttachmentId)
        {
            if (!this.Exists(pageTemplateAttachmentId))
            {
                throw new ArgumentException("此记录不存在!");
            }
            var oldDto = this.Get(pageTemplateAttachmentId);
            var result = this.pageTemplateAttachmentData.Delete(pageTemplateAttachmentId).GetAwaiter().GetResult();
            string applicationRootDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;                         //当前系统根目录
            string websiteRootDirectory = Path.Combine(applicationRootDirectory, configuration["WebsiteName"]);                      //当前网站目录
            string defaultHost = configuration["DefaultHost"];
            var filePath = oldDto.FileAddress.Replace(defaultHost.TrimEnd('/'), websiteRootDirectory);
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            this.redisService.DeleteMultipleKey(key, false);
            return result;
        }
        #endregion

        #region 获取页面模板附件
        public PageTemplateAttachmentDto Get(int pageTemplateAttachmentId)
        {
            string cacheKey = this.redisService.GetKey(key, pageTemplateAttachmentId);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.pageTemplateAttachmentData.GetEntity(pageTemplateAttachmentId).GetAwaiter().GetResult();
                return data;
            }, TimeSpan.FromMinutes(30));
            return result.As<PageTemplateAttachmentDto>();
        }
        #endregion

        #region 获取页面模板附件列表
        public IEnumerable<PageTemplateAttachmentDto> GetList(long pageTemplateId)
        {
            string cacheKey = this.redisService.GetKey(key, pageTemplateId);

           var result = this.redisService.TryGet(cacheKey, () =>
            {
                return this.pageTemplateAttachmentData.GetList(pageTemplateId).GetAwaiter().GetResult();
            }, TimeSpan.FromMinutes(30));
            return result.As<IEnumerable<PageTemplateAttachmentDto>>();
        }
        #endregion

        #region 获取页面模板附件分页
        public PageableList<PageTemplateAttachmentDto> Query(long pageTemplateId,DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key, pageTemplateId, start, end, sortName, ascending, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = this.pageTemplateAttachmentData.Query(pageTemplateId, start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
                return new PageableList<PageTemplateAttachmentDto>
                {
                    Count = data.Item2,
                    Items = data.Item1.As<IEnumerable<PageTemplateAttachmentDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now
                };
            }, TimeSpan.FromMinutes(30));

            return result;
        }
        #endregion
    }
}